<template>
  <div class="filter">
    <t-drawer
      size="695px"
      :visible.sync="visible"
      :closeBtn="false"
      :close-on-overlay-click="false"
    >
      <template #header>
        <div class="drawer-head" @click="close">
          <p class="chevron-left">
            <icon-font name="chevron-left" size="18px"/>
          </p>
          <h3>{{ header }}</h3>
        </div>
      </template>
      <template #footer>
        <!--<div class="footer">-->
          <!--<t-button v-if="current !== 1" theme="default" @click="previous">上一步</t-button>-->
          <!--<t-button v-if="current !== tabs.length" theme="primary" @click="next">下一步</t-button>-->
          <!--<t-button v-if="current === tabs.length" :theme="confirmBtn.theme" :loading="confirmBtn.loading" @click="submit">-->
          <!--  {{ confirmBtn.text }}-->
          <!--</t-button>-->
        <t-space size="8px">
          <t-button theme="primary" class="" :theme="confirmBtn.theme" :loading="confirmBtn.loading" @click="submit">{{ confirmBtn.content }}</t-button>
          <t-button theme="default" class="" @click="close">取消</t-button>
          <t-checkbox v-if="type === 'add'" :value="again" @change="changeAgain">继续录入</t-checkbox>
        </t-space>
        <!--</div>-->
      </template>
      <div v-if="visible" class="product-add">
        <!--<tab-list :current="current" :tabs="tabs" @change="changeTab"></tab-list>-->
        <t-tabs v-model="current" :list="tabs"/>
        <!-- 基础信息 -->
        <base-info v-show="current === 1" ref="base"></base-info>
        <!-- 租赁设置 -->
        <product-lease v-show="current === 2" ref="lease"></product-lease>
        <!-- 售卖设置 -->
        <product-sell v-show="current === 3" ref="sell"></product-sell>
        <!-- 产品图片 -->
        <product-images v-show="current === 4" ref="images"></product-images>
        <!-- 产品详情 -->
        <product-detail v-show="current === 5" ref="detail"></product-detail>
        <!-- 配件清单 -->
        <product-inventory v-show="current === 6" ref="inventory"></product-inventory>
        <!-- 关联产品 -->
        <related-products v-show="current === 7" ref="related" @addProduct="addProduct"></related-products>
        <!-- 营销设置 -->
        <marketing-settings v-show="current === 8" ref="marketing"></marketing-settings>
        <!-- 分享设置 -->
        <share-setting v-show="current === 9" ref="share"></share-setting>
        <!-- 其他设置 -->
        <additional-content v-show="current === 10" ref="additional"></additional-content>
      </div>
    </t-drawer>

    <product-list ref="relationList" @confirm="confirmProduct" ></product-list>
  </div>
</template>

<script>
import {IconFont} from "tdesign-icons-vue";
import BaseInfo from "@/pages/product/list/add/components/base-info.vue";
import ProductInventory from "@/pages/product/list/add/components/product-inventory.vue";
import ProductLease from "@/pages/product/list/add/components/product-lease.vue";
import ProductSell from "@/pages/product/list/add/components/product-sell.vue";
import ProductImages from "@/pages/product/list/add/components/product-images.vue";
import ProductDetail from "@/pages/product/list/add/components/product-detail.vue";
import RelatedProducts from "@/pages/product/list/add/components/related-products.vue";
import ShareSetting from "@/pages/product/list/add/components/share-setting.vue";
import MarketingSettings from "@/pages/product/list/add/components/marketing-settings.vue";
import AdditionalContent from "@/pages/product/list/add/components/additional-content.vue";
import {productCreateApi, productDetailApi, productEditApi} from "@/api/product";
import ProductList from "@/components/product-list/index.vue";

export default {
  name: 'ProductAdd',
  components: {
    ProductList,
    AdditionalContent,
    MarketingSettings,
    RelatedProducts,
    IconFont,
    ProductDetail,
    ShareSetting,
    ProductImages,
    ProductInventory,
    ProductLease,
    ProductSell,
    BaseInfo,
    //TabList
  },
  data() {
    return {
      visible: false,
      header: '新增产品',
      current: 1,
      tabs: [
        {label: '产品基础信息', value: 1},
        {label: '租赁设置', value: 2},
        {label: '售卖设置', value: 3},
        {label: '产品图片', value: 4},
        {label: '产品详情', value: 5},
        {label: '配件清单', value: 6},
        {label: '关联产品', value: 7},
        {label: '营销设置', value: 8},
        //{label: '分享设置', value: 9},
        {label: '其他设置', value: 10},
      ],
      again: false,
      confirmBtn: {
        content: '保存',
        theme: 'primary',
        loading: false
      },
      editId: '',
      type: 'add',
    }
  },
  methods: {
    addProduct() {
      this.$refs.relationList.open()
    },
    confirmProduct(list) {
      this.$refs.related.formData.relation_data = [...this.$refs.related.formData.relation_data, ...list]
      console.log(this.$refs.related.formData.relation_data)
    },
    // 切换tab
    changeTab(value) {
      this.current = value
    },
    // 上一步
    previous() {
      this.current--
    },
    // 下一步
    next() {
      this.current++
    },
    changeAgain(value) {
      this.again = value
    },
    // 提交
    async submit() {
      const base = await this.$refs.base.submit();
      const lease = await this.$refs.lease.submit();
      const sell = await this.$refs.sell.submit();
      const images = await this.$refs.images.submit();
      const detail = await this.$refs.detail.submit();
      const inventory = await this.$refs.inventory.submit();
      const related = await this.$refs.related.submit();
      const marketing = await this.$refs.marketing.submit();
      const share = await this.$refs.share.submit();
      const additional = await this.$refs.additional.submit();
      // 对象合并
      const valid = Object.assign(
        {},
        base,
        lease,
        sell,
        images,
        detail,
        inventory,
        related,
        marketing,
        //share,
        additional
      );
      // 判断是否验证通过
      if (!Object.keys(valid).length) {
        this.handleSubmit()
      } else {
        this.$message.error('请完善信息')
        if (Object.keys(base).length) {
          this.current = 1
          } else if (Object.keys(lease).length) {
            this.current = 2
          } else if (Object.keys(sell).length) {
            this.current = 3
          } else if (Object.keys(images).length) {
            this.current = 4
          } else if (Object.keys(detail).length) {
            this.current = 5
        } else if (Object.keys(inventory).length) {
          this.current = 6
          } else if (Object.keys(related).length) {
            this.current = 7
          } else if (Object.keys(marketing).length) {
            this.current = 8
          } else if (Object.keys(share).length) {
            this.current = 9
        } else if (Object.keys(additional).length) {
          this.current = 10
        }
      }
    },
    handleSubmit() {
      const base = this.$refs.base.formData;
      const lease = this.$refs.lease.formData;
      const sell = this.$refs.sell.formData;
      const images = this.$refs.images.formData;
      const detail = this.$refs.detail.formData;
      const inventory = this.$refs.inventory.formData;
      const related = this.$refs.related.formData;
      const marketing = this.$refs.marketing.formData;
      const share = this.$refs.share.formData;
      const additional = this.$refs.additional.formData;
      // 对象合并
      const params = Object.assign(
        {},
        base,
        lease,
        sell,
        images,
        detail,
        inventory,
        related,
        marketing,
        //share,
        additional
      );
      this.confirmBtn.loading = true
      this.confirmBtn.text = '保存中'
      // 幻灯图组
      if (params.images_data) {
        params.images_data = JSON.stringify(params.images_data)
      }
      // 标签
      if (params.label_data) {
        params.label_data = JSON.stringify(params.label_data)
      }
      // 配件清单
      if (params.params_data) {
        params.params_data = JSON.stringify(params.params_data)
      }
      // 关联产品
      if (params.relation_data) {
        console.log('params.relation_data', params.relation_data)
        const ids = params.relation_data.map(item=> item.id)
        //params.relation_data = JSON.stringify(params.relation_data)
        params.relation_data = ids.join(',')
      }
      params.deliver_data = params.deliver_data.join(',')
      params.safeguard_data = params.safeguard_data.join(',')
      if (this.editId) {
        params.id = this.editId
      }
      const request = this.type === 'edit' ? productEditApi : productCreateApi
      request(params).then(res => {
        this.$message.success(this.type === 'edit' ? '编辑成功' : '新增成功')
        this.$emit('refresh')
        if (!this.again) {
          this.close()
        } else {
          this.resetFormData()
        }
      }).catch(err => {
        console.log('err', err)
      }).finally(() => {
        this.confirmBtn.loading = false
        this.confirmBtn.text = '保存'
      })
    },
    resetFormData(){
      this.$refs.base.reset()
      this.$refs.lease.reset()
      this.$refs.sell.reset()
      this.$refs.images.reset()
      this.$refs.detail.reset()
      this.$refs.inventory.reset()
      this.$refs.related.reset()
      this.$refs.marketing.reset()
      this.$refs.share.reset()
      this.$refs.additional.reset()
    },
    getDetail() {
      productDetailApi({id: this.editId}).then(res => {
        const {data} = res
        this.$refs.base.formData = {
          //brand_id: data.brand_id, // 品牌
          classify_id: data.classify_id, // 分类
          title: data.title, // 标题
          unit_id: data.unit_id, // 单位
          //selling_price: data.selling_price, // 售价
          ean: data.ean, // EAN条形码
          upc: data.upc, // UPC条形码
          thumb: data.thumb, // 缩略图
          //name: data.name, // 名称
          //sn: data.sn, // 编号
          sort: data.sort, // 排序
          //status: data.status, // 状态
        }
        this.$refs.lease.formData = {
          is_rent: data.is_rent, // 是否可租
          day_rent: data.day_rent, // 日租价
          cash_pledge: data.cash_pledge, // 租赁押金
          //is_selling: data.is_selling, // 是否可售
          //selling_price: data.selling_price, // 售卖价
          //is_stock: data.is_stock,  // 库存模式
          //stock_num: data.stock_num,  // 库存数量
        }
        this.$refs.sell.formData = {
          //is_rent: data.is_rent, // 是否可租
          //day_rent: data.day_rent, // 日租价
          //cash_pledge: data.cash_pledge, // 租赁押金
          is_selling: data.is_selling, // 是否可售
          selling_price: data.selling_price, // 售卖价
          //is_stock: data.is_stock,  // 库存模式
          //stock_num: data.stock_num,  // 库存数量
        }
        this.$refs.images.formData = {
          //thumb: data.thumb || '', // 小缩略图
          //thumb_big: data.thumb_big || '', // 大缩略图
          images_data: data.images_data ? JSON.parse(data.images_data) : [], // 幻灯图组
          //video: data.video || '', // 视频
        }
        this.$refs.detail.formData = {
          //label_data: data.label_data ? JSON.parse(data.label_data) : [], // 标签
          content: data.content, // 产品详情
          notice: data.notice, // 分类
        }
        this.$refs.inventory.formData = {
          params_data: data.params_data ? JSON.parse(data.params_data) : [{sn: '', title: '', num: ''}], // 配件清单
        }
        this.$refs.related.formData = {
          relation_data: data.relation ? data.relation : [], // 关联产品
        }
        this.$refs.marketing.formData = {
          hot_level: data.hot_level, // 推荐等级
          virtual_rent: data.virtual_rent, // 租赁数
          virtual_browse: data.virtual_browse, // 浏览数
          virtual_sales: data.virtual_sales, // 虚拟销量
        }
        this.$refs.share.formData = {
          share_status: data.share_status, // 是否允许分享
          share_title: data.share_title, // 分享标题
          share_desc: data.share_desc, // 分享描述
          share_image: data.share_image, // 分享图片
        }
        this.$refs.additional.formData = {
          // 字符串转数组并转换成数字类型
          deliver_data: data.deliver_data ? data.deliver_data.split(',').map(Number) : [], // 发货说明
          safeguard_data: data.safeguard_data ? data.safeguard_data.split(',').map(Number) : [], // 平台保障
          msg: data.msg, //
          desc: data.desc, //
          config_data: data.config_data, //配置数据（自定义JSON数据）
        }
        if (this.type === 'edit') {
          this.header = '编辑产品'
        }
      }).catch(err => {
        console.log('err', err)
      })
    },
    open(type, data = {}) {
      this.current = 1
      this.editId = data.id
      this.type = type
      this.header = '新增产品'
      if (this.type === 'edit' || this.type === 'copy') {
        this.getDetail()
      }
      this.again = false
      this.visible = true
    },
    close() {
      this.visible = false
    }
  }
}
</script>

<style lang="less" scoped>
.footer {
  display: flex;
  align-items: center;
  gap: 8px;

  .foot-btn {
    width: 132px;
    height: 42px;
    color: #FFFFFF;
    border-radius: var(--td-radius-medium);
  }

  .cancel-btn {
    background-color: #B8B8B8;
  }
}

/deep/ .t-drawer__header {
  padding: 0 var(--td-comp-paddingLR-xl);
}

/deep/ .t-drawer__body {
  padding: var(--td-comp-paddingTB-l) var(--td-comp-paddingLR-xl);
  padding-top: 0;
}

/deep/ .t-drawer__footer {
  padding: var(--td-comp-paddingTB-l) var(--td-comp-paddingLR-xl);
}

</style>
